package workexp.alg.question.linklist;

import org.junit.Test;
import workexp.alg.env.ListNode;

public class MergeTwoLists {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null)
            return list2;
        if (list2 == null)
            return list1;
        ListNode p1,p2,current,result;
        p1=list1;
        p2=list2;
        if(compare(list1,list2)){
            result=list2;
        }else{
            result=list1;
        }
        current = new ListNode();
        while(p1!=null&&p2!=null){
            if(compare(p1,p2)){
                current.next=p2;
                p2=p2.next;
            }else{
                current.next=p1;
                p1=p1.next;
            }
            current=current.next;
        }
        if(p1!=null){
            current.next=p1;
        }else{
            current.next=p2;
        }
        return result;
    }

    /**
     * list1大于list2返回true
     * @param list1
     * @param list2
     * @return
     */
    public boolean compare(ListNode list1, ListNode list2){
        return list1.val>list2.val;
    }

    @Test
    public void test(){
        ListNode head = ListNode.genList(new int[]{1,3,5,7});
        ListNode head2 = ListNode.genList(new int[]{2,4,6,8});
        ListNode res = mergeTwoLists(head,head2);
        res.printLinkList();
    }
}
